package com.uduemc.biso.node.web.api.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.core.utils.ResultUtil;
import com.uduemc.biso.node.core.common.entities.FormData;
import com.uduemc.biso.node.core.common.entities.FormInfoData;
import com.uduemc.biso.node.core.common.feign.CFormFeign;
import com.uduemc.biso.node.core.common.feign.CFormInfoFeign;
import com.uduemc.biso.node.core.common.sysconfig.ProductSysConfig;
import com.uduemc.biso.node.core.common.udinpojo.ComponentFormtextData;
import com.uduemc.biso.node.core.common.udinpojo.ComponentFormtextareaData;
import com.uduemc.biso.node.core.common.udinpojo.ContainerFormboxData;
import com.uduemc.biso.node.core.common.udinpojo.ContainerFormcolData;
import com.uduemc.biso.node.core.common.udinpojo.ContainerFormmainboxData;
import com.uduemc.biso.node.core.common.udinpojo.common.ComponentFormRules;
import com.uduemc.biso.node.core.common.udinpojo.componentformtext.ComponentFormtextDataText;
import com.uduemc.biso.node.core.common.udinpojo.componentformtextarea.ComponentFormtextareaDataText;
import com.uduemc.biso.node.core.dto.FeignFindInfoFormInfoData;
import com.uduemc.biso.node.core.dto.FeignResponseFormInfoTotal;
import com.uduemc.biso.node.core.dto.sforminfo.FeignSFormInfoSystemItemName;
import com.uduemc.biso.node.core.dto.sforminfo.FeignSFormInfoSystemName;
import com.uduemc.biso.node.core.entities.SComponentForm;
import com.uduemc.biso.node.core.entities.SContainerForm;
import com.uduemc.biso.node.core.entities.SContainerQuoteForm;
import com.uduemc.biso.node.core.entities.SForm;
import com.uduemc.biso.node.core.entities.SFormInfo;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.feign.SFormFeign;
import com.uduemc.biso.node.core.feign.SFormInfoFeign;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.dto.RequestFormInfoDataList;
import com.uduemc.biso.node.web.api.dto.RequestGetFormCompSetup;
import com.uduemc.biso.node.web.api.dto.form.FormCompSetup;
import com.uduemc.biso.node.web.api.dto.form.FormCompSetupRule;
import com.uduemc.biso.node.web.api.dto.form.FormContSetup;
import com.uduemc.biso.node.web.api.pojo.ResponseTableInfoForm;
import com.uduemc.biso.node.web.api.service.ContainerService;
import com.uduemc.biso.node.web.api.service.FormService;
import com.uduemc.biso.node.web.api.service.SystemService;
import com.uduemc.biso.node.web.api.service.fegin.SComponentFormService;
import com.uduemc.biso.node.web.api.service.fegin.SContainerFormService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class FormServiceImpl implements FormService {

	public static final int PageForm = 1;
	public static final int SystemForm = 2;

	@Resource
	private SFormFeign sFormFeign;

	@Resource
	private CFormFeign cFormFeign;

	@Resource
	private CFormInfoFeign cFormInfoFeign;

	@Resource
	private SFormInfoFeign sFormInfoFeign;

	@Resource
	private ContainerService containerServiceImpl;

	@Resource
	private SystemService systemServiceImpl;

	@Resource
	private RequestHolder requestHolder;

	@Resource
	private ObjectMapper objectMapper;

	@Resource
	private SContainerFormService sContainerFormServiceImpl;

	@Resource
	private SComponentFormService sComponentFormServiceImpl;

	@Override
	public List<SForm> getCurrentInfos(int type) throws IOException {
		return getInfos(requestHolder.getHost().getId(), requestHolder.getCurrentSite().getId(), type);
	}

	@Override
	public List<SForm> getCurrentInfos() throws IOException {
		return getCurrentInfos(-1);
	}

	@Override
	public List<SForm> getInfos(long hostId, long siteId, int type) throws IOException {
		RestResult restResult = sFormFeign.findInfosByHostSiteIdType(hostId, siteId, type);
		@SuppressWarnings("unchecked")
		ArrayList<SForm> data = (ArrayList<SForm>) RestResultUtil.data(restResult, new TypeReference<ArrayList<SForm>>() {
		});
		return data;
	}

	@Override
	public List<SForm> getInfos(long hostId, long siteId) throws IOException {
		return getInfos(hostId, siteId, -1);
	}

	@Override
	public SForm getInfo(long id, long hostId, long siteId) throws IOException {
		RestResult restResult = sFormFeign.findByHostSiteIdAndId(id, hostId, siteId);
		SForm data = RestResultUtil.data(restResult, SForm.class);
		return data;
	}

	@Override
	public SForm getCurrentInfo(long id) throws IOException {
		Long hostId = requestHolder.getHost().getId();
		Long siteId = requestHolder.getCurrentSite().getId();
		return getInfo(id, hostId, siteId);
	}

	@Override
	public FormData createForm(String name) throws IOException {
		Long hostId = requestHolder.getHost().getId();
		Long siteId = requestHolder.getCurrentSite().getId();
		SForm sForm = new SForm();
		sForm.setHostId(hostId).setSiteId(siteId).setType(1).setName(name).setConfig("");

		RestResult insert = sFormFeign.insert(sForm);
		SForm data = RestResultUtil.data(insert, SForm.class);
		if (data == null) {
			return null;
		}
		return getCurrentFormDataByFormId(data.getId());
	}

	@Override
	public FormData createSystemForm(String name, SSystem sSystem) throws IOException {
		Long hostId = requestHolder.getHost().getId();
		Long siteId = requestHolder.getCurrentSite().getId();
		SForm sForm = new SForm();
		sForm.setHostId(hostId).setSiteId(siteId).setType(2).setName(name).setConfig("");

		RestResult insert = sFormFeign.insert(sForm);
		SForm data = RestResultUtil.data(insert, SForm.class);
		if (data == null) {
			return null;
		}
		// 创建好后自动创建默认的表单结构
		createDefaultSystemForm(data);

		if (sSystem != null) {
			sSystem.setFormId(data.getId());
			systemServiceImpl.updateSSystem(sSystem);
		}
		return getCurrentFormDataByFormId(data.getId());
	}

	@Override
	public SForm update(SForm sForm) throws IOException {
		RestResult restResult = sFormFeign.updateById(sForm);
		SForm data = RestResultUtil.data(restResult, SForm.class);
		return data;
	}

	@Override
	public FormData getCurrentFormDataByFormId(long formId) throws IOException {
		return getFormDataByFormId(formId, requestHolder.getHost().getId(), requestHolder.getCurrentSite().getId());
	}

	@Override
	public FormData getFormDataByFormId(long formId, long hostId, long siteId) throws IOException {
		RestResult restResult = cFormFeign.findOneByFormHostSiteId(formId, hostId, siteId);
		FormData data = RestResultUtil.data(restResult, FormData.class);
		if (data != null) {
			SForm sForm = data.getForm();
			Integer type = sForm.getType();
			if (type != null && type.intValue() == SystemForm) {
				List<SSystem> listSSystem = systemServiceImpl.getInfosByHostSiteFormId(sForm.getHostId(), sForm.getSiteId(), sForm.getId());
				data.setMount(listSSystem);
			}
		}
		return data;
	}

	@Override
	public List<ResponseTableInfoForm> responseTableInfoFormByType(int type) throws IOException {
		List<ResponseTableInfoForm> result = new ArrayList<>();
		List<SForm> listSForm = getCurrentInfos(type);
		if (CollUtil.isEmpty(listSForm)) {
			return null;
		}
		List<Long> formIds = new ArrayList<>();
		List<SContainerQuoteForm> listSContainerQuoteForm = null;
		for (SForm sForm : listSForm) {
			formIds.add(sForm.getId());

			listSContainerQuoteForm = containerServiceImpl.getCurrentSContainerQuoteFormByHostFormId(requestHolder.getHost().getId(), sForm.getId());

			ResponseTableInfoForm responseTableInfoForm = new ResponseTableInfoForm();
			responseTableInfoForm.setId(sForm.getId()).setFormName(sForm.getName()).setCreateAt(sForm.getCreateAt());
			responseTableInfoForm.setQuote(CollUtil.isEmpty(listSContainerQuoteForm) ? 0 : listSContainerQuoteForm.size());

			// 如果 type == 2，获取挂载的系统数据列表
			if (type == SystemForm) {
				List<SSystem> listSSystem = systemServiceImpl.getInfosByHostSiteFormId(sForm.getHostId(), sForm.getSiteId(), sForm.getId());
				responseTableInfoForm.setMount(listSSystem);
			}

			result.add(responseTableInfoForm);
		}

		// 数据总数
		RestResult restResult = cFormInfoFeign.total(requestHolder.getHost().getId(), formIds);
		@SuppressWarnings("unchecked")
		List<FeignResponseFormInfoTotal> listFeignResponseFormInfoTotal = (List<FeignResponseFormInfoTotal>) RestResultUtil.data(restResult,
				new TypeReference<List<FeignResponseFormInfoTotal>>() {
				});
		if (CollUtil.isNotEmpty(listFeignResponseFormInfoTotal)) {
			for (ResponseTableInfoForm item : result) {
				FeignResponseFormInfoTotal feignResponseFormInfoTotal = null;
				for (FeignResponseFormInfoTotal formInfoTotal : listFeignResponseFormInfoTotal) {
					if (formInfoTotal.getFormId() == item.getId()) {
						feignResponseFormInfoTotal = formInfoTotal;
					}
				}
				if (feignResponseFormInfoTotal != null) {
					item.setTotal(feignResponseFormInfoTotal.getTotal());
				} else {
					item.setTotal(0);
				}
			}
		}

		return result;
	}

	@Override
	public SForm deleteCurrnetFormData(long formId) throws IOException {
		RestResult restResult = cFormFeign.deleteFormByFormHostSiteId(formId, requestHolder.getHost().getId(), requestHolder.getCurrentSite().getId());
		SForm data = RestResultUtil.data(restResult, SForm.class);
		return data;
	}

	@Override
	public SForm deleteFormData(SForm sForm) throws IOException {
		Long hostId = requestHolder.getHost().getId();
		Long siteId = requestHolder.getCurrentSite().getId();
		if (sForm == null) {
			return null;
		}
		Long sFormHostId = sForm.getHostId();
		Long sFormSiteId = sForm.getSiteId();
		if (sFormHostId == null || hostId == null || sFormHostId.longValue() != hostId.longValue()) {
			return null;
		}

		if (sFormSiteId == null || siteId == null || sFormSiteId.longValue() != siteId.longValue()) {
			return null;
		}

		SForm deleteSForm = deleteCurrnetFormData(sForm.getId());
		if (deleteSForm == null) {
			return null;
		}

		Integer type = deleteSForm.getType();
		if (type != null && type.intValue() == SystemForm) {
			// 删除的是系统表单，需要重置系统中的表单数据Id为0
			systemServiceImpl.updateSSystemFormIdZero(deleteSForm);
		}

		return deleteSForm;
	}

	@Override
	public PageInfo<FormInfoData> getPageInfoFormInfoDataByQuery(RequestFormInfoDataList requestFormInfoDataList) throws IOException {
		FeignFindInfoFormInfoData feignFindInfoFormInfoData = requestFormInfoDataList.getFeignFindInfoFormInfoData(requestHolder.getHost().getId(),
				requestHolder.getCurrentSite().getId());
		RestResult restResult = cFormInfoFeign.findInfosByFormIdSearchPage(feignFindInfoFormInfoData);
		@SuppressWarnings("unchecked")
		PageInfo<FormInfoData> data = (PageInfo<FormInfoData>) RestResultUtil.data(restResult, new TypeReference<PageInfo<FormInfoData>>() {
		});
		return data;
	}

	@Override
	public SFormInfo getCurrentSFormInfoById(long id) throws IOException {
		RestResult restResult = sFormInfoFeign.findOne(id);
		SFormInfo data = RestResultUtil.data(restResult, SFormInfo.class);
		if (data != null && data.getHostId().longValue() == requestHolder.getHost().getId().longValue()
				&& data.getSiteId().longValue() == requestHolder.getCurrentSite().getId().longValue()) {
			return data;
		}
		return null;
	}

	@Override
	public SFormInfo deleteFormInfo(SFormInfo sFormInfo) throws IOException {
		RestResult restResult = cFormInfoFeign.deleteFornInfoByHostFormInfoId(sFormInfo.getHostId(), sFormInfo.getFormId(), sFormInfo.getId());
		SFormInfo data = RestResultUtil.data(restResult, SFormInfo.class);
		return data;
	}

	@Override
	public List<String> formInfoSystemName(long formId, String listKeywords) throws IOException {
		long hostId = requestHolder.getHost().getId();
		long siteId = requestHolder.getCurrentSite().getId();
		FeignSFormInfoSystemName sFormInfoSystemName = FeignSFormInfoSystemName.builder().hostId(hostId).siteId(siteId).formId(formId)
				.likeKeywords(listKeywords).build();
		RestResult restResult = sFormInfoFeign.systemName(sFormInfoSystemName);
		@SuppressWarnings("unchecked")
		ArrayList<String> list = (ArrayList<String>) ResultUtil.data(restResult, new TypeReference<List<String>>() {
		});
		return list;
	}

	@Override
	public List<String> formInfoSystemItemName(long formId, String systemName, String listKeywords) throws IOException {
		long hostId = requestHolder.getHost().getId();
		long siteId = requestHolder.getCurrentSite().getId();
		FeignSFormInfoSystemItemName sFormInfoSystemItemName = FeignSFormInfoSystemItemName.builder().hostId(hostId).siteId(siteId).formId(formId)
				.systemName(systemName).likeKeywords(listKeywords).build();
		RestResult restResult = sFormInfoFeign.systemItemName(sFormInfoSystemItemName);
		@SuppressWarnings("unchecked")
		ArrayList<String> list = (ArrayList<String>) ResultUtil.data(restResult, new TypeReference<List<String>>() {
		});
		return list;
	}

	@Override
	public JsonResult mountSystem(long formId, String systemIds) throws IOException {
		SForm sForm = getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}
		if (StrUtil.isBlank(systemIds)) {
			return JsonResult.illegal();
		}
		List<String> systemIdsString = StrUtil.split(systemIds, ",");
		if (CollUtil.isEmpty(systemIdsString)) {
			return JsonResult.illegal();
		}
		List<Long> systemIdsLong = CollUtil.map(systemIdsString, item -> {
			if (NumberUtil.isLong(item)) {
				return Long.valueOf(item);
			}
			return 0L;
		}, true);
		if (CollUtil.isEmpty(systemIdsLong)) {
			return JsonResult.illegal();
		}
		List<Long> systemIdsFilter = CollUtil.filter(systemIdsLong, item -> item > 0);
		if (CollUtil.isEmpty(systemIdsFilter)) {
			return JsonResult.illegal();
		}

		List<SSystem> listSystem = new ArrayList<>(systemIdsFilter.size());
		for (Long systemId : systemIdsFilter) {
			SSystem sSystem = systemServiceImpl.getCurrentInfoById(systemId);
			if (systemServiceImpl.allowMountForm(sSystem)) {
				// 修改
				sSystem.setFormId(sForm.getId());
				SSystem updateSSystem = systemServiceImpl.updateSSystem(sSystem);
				if (updateSSystem != null) {
					listSystem.add(updateSSystem);
				}
			}
		}
		if (CollUtil.isEmpty(listSystem)) {
			return JsonResult.illegal();
		}

		return JsonResult.ok(listSystem);
	}

	/**
	 * 默认的系统留言表单需要创建6个容器以及6个表单组件
	 *
	 * @param sForm
	 */
	@Override
	public void createDefaultSystemForm(SForm sForm) throws IOException {
		Long hostId = sForm.getHostId();
		Long siteId = sForm.getSiteId();
		Long formId = sForm.getId();
		String sFormName = sForm.getName();
		// 首先构建容器的数据

		// 主容器
		SContainerForm formMainbox = new SContainerForm();
		String formMainboxConfig = objectMapper.writeValueAsString(ContainerFormmainboxData.makeDefault());
		formMainbox.setHostId(hostId).setSiteId(siteId).setFormId(formId).setBoxId(0L).setParentId(0L).setTypeId(5L).setStatus((short) 0).setName(sFormName)
				.setOrderNum(1).setConfig(formMainboxConfig);
		SContainerForm insertFormMainbox = sContainerFormServiceImpl.insert(formMainbox);
		if (insertFormMainbox == null || insertFormMainbox.getId() == null) {
			throw new RuntimeException("写入表单主容器数据失败！formMainbox: " + formMainbox);
		}
		Long boxId = insertFormMainbox.getId();

		// 添加第一层的栅格和容器
		SContainerForm topCol = new SContainerForm();
		ContainerFormcolData topColConfig = ContainerFormcolData.makeDefault();
		topCol.setHostId(hostId).setSiteId(siteId).setFormId(formId).setBoxId(boxId).setParentId(insertFormMainbox.getId()).setTypeId(6L).setStatus((short) 0)
				.setName("").setOrderNum(1).setConfig(objectMapper.writeValueAsString(topColConfig));
		SContainerForm insertTopCol = sContainerFormServiceImpl.insert(topCol);
		if (insertTopCol == null || insertTopCol.getId() == null) {
			throw new RuntimeException("写入表单主容器下的 col 数据失败！topCol: " + topCol);
		}
		SContainerForm topBox = new SContainerForm();
		ContainerFormboxData topBoxConfig = ContainerFormboxData.makeDefault();
		topBox.setHostId(hostId).setSiteId(siteId).setFormId(formId).setBoxId(boxId).setParentId(insertTopCol.getId()).setTypeId(7L).setStatus((short) 0)
				.setName("").setOrderNum(1).setConfig(objectMapper.writeValueAsString(topBoxConfig));
		SContainerForm insertTopBox = sContainerFormServiceImpl.insert(topBox);
		if (insertTopBox == null || insertTopBox.getId() == null) {
			throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
		}

		ComponentFormtextData componentConfig;
		String textLabel;
		SComponentForm sComponentForm;
		// 添加第一个行的栅格、容器、组件
		SContainerForm rowBox = createDefaultSystemFormRowBox(insertTopBox, 1);
		if (rowBox != null && rowBox.getId() > 0) {
			textLabel = "昵称";
			componentConfig = ComponentFormtextData.makeDefault(textLabel);
			sComponentForm = new SComponentForm();
			sComponentForm.setHostId(hostId).setSiteId(siteId).setFormId(formId).setContainerId(rowBox.getId()).setContainerBoxId(boxId).setTypeId(20L)
					.setName("").setLabel(textLabel).setStatus((short) 0).setConfig(objectMapper.writeValueAsString(componentConfig));
			SComponentForm insertSComponentForm = sComponentFormServiceImpl.insert(sComponentForm);
			if (insertSComponentForm == null || insertSComponentForm.getId() == null) {
				throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
			}
		}

		// 添加第二个行的栅格、容器、组件
		rowBox = createDefaultSystemFormRowBox(insertTopBox, 2);
		if (rowBox != null && rowBox.getId() > 0) {
			textLabel = "电话号码";
			componentConfig = ComponentFormtextData.makeDefault(textLabel);
			sComponentForm = new SComponentForm();
			sComponentForm.setHostId(hostId).setSiteId(siteId).setFormId(formId).setContainerId(rowBox.getId()).setContainerBoxId(boxId).setTypeId(20L)
					.setName("").setLabel(textLabel).setStatus((short) 0).setConfig(objectMapper.writeValueAsString(componentConfig));
			SComponentForm insertSComponentForm = sComponentFormServiceImpl.insert(sComponentForm);
			if (insertSComponentForm == null || insertSComponentForm.getId() == null) {
				throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
			}
		}

		// 添加第三个行的栅格、容器、组件
		rowBox = createDefaultSystemFormRowBox(insertTopBox, 3);
		if (rowBox != null && rowBox.getId() > 0) {
			textLabel = "电子邮箱";
			componentConfig = ComponentFormtextData.makeDefault(textLabel);
			sComponentForm = new SComponentForm();
			sComponentForm.setHostId(hostId).setSiteId(siteId).setFormId(formId).setContainerId(rowBox.getId()).setContainerBoxId(boxId).setTypeId(20L)
					.setName("").setLabel(textLabel).setStatus((short) 0).setConfig(objectMapper.writeValueAsString(componentConfig));
			SComponentForm insertSComponentForm = sComponentFormServiceImpl.insert(sComponentForm);
			if (insertSComponentForm == null || insertSComponentForm.getId() == null) {
				throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
			}
		}

		// 添加第四个行的栅格、容器、组件
		rowBox = createDefaultSystemFormRowBox(insertTopBox, 4);
		if (rowBox != null && rowBox.getId() > 0) {
			textLabel = "公司名称";
			componentConfig = ComponentFormtextData.makeDefault(textLabel);
			sComponentForm = new SComponentForm();
			sComponentForm.setHostId(hostId).setSiteId(siteId).setFormId(formId).setContainerId(rowBox.getId()).setContainerBoxId(boxId).setTypeId(20L)
					.setName("").setLabel(textLabel).setStatus((short) 0).setConfig(objectMapper.writeValueAsString(componentConfig));
			SComponentForm insertSComponentForm = sComponentFormServiceImpl.insert(sComponentForm);
			if (insertSComponentForm == null || insertSComponentForm.getId() == null) {
				throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
			}
		}

		// 添加第五个行的栅格、容器、组件
		rowBox = createDefaultSystemFormRowBox(insertTopBox, 5);
		if (rowBox != null && rowBox.getId() > 0) {
			textLabel = "地址";
			componentConfig = ComponentFormtextData.makeDefault(textLabel);
			sComponentForm = new SComponentForm();
			sComponentForm.setHostId(hostId).setSiteId(siteId).setFormId(formId).setContainerId(rowBox.getId()).setContainerBoxId(boxId).setTypeId(20L)
					.setName("").setLabel(textLabel).setStatus((short) 0).setConfig(objectMapper.writeValueAsString(componentConfig));
			SComponentForm insertSComponentForm = sComponentFormServiceImpl.insert(sComponentForm);
			if (insertSComponentForm == null || insertSComponentForm.getId() == null) {
				throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
			}
		}

		// 添加第六个行的栅格、容器、组件
		rowBox = createDefaultSystemFormRowBox(insertTopBox, 6);
		if (rowBox != null && rowBox.getId() > 0) {
			textLabel = "留言";
			ComponentFormtextareaData textareaConfig = ComponentFormtextareaData.makeDefault(1, textLabel);
			sComponentForm = new SComponentForm();
			sComponentForm.setHostId(hostId).setSiteId(siteId).setFormId(formId).setContainerId(rowBox.getId()).setContainerBoxId(boxId).setTypeId(21L)
					.setName("").setLabel(textLabel).setStatus((short) 0).setConfig(objectMapper.writeValueAsString(textareaConfig));
			SComponentForm insertSComponentForm = sComponentFormServiceImpl.insert(sComponentForm);
			if (insertSComponentForm == null || insertSComponentForm.getId() == null) {
				throw new RuntimeException("写入表单主容器下col 的 box 数据失败！topBox: " + topBox);
			}
		}
	}

	SContainerForm createDefaultSystemFormRowBox(SContainerForm topBox, int colOrder) throws IOException {
		Long hostId = topBox.getHostId();
		Long siteId = topBox.getSiteId();
		Long formId = topBox.getFormId();
		Long boxId = topBox.getBoxId();

		// 添加第一层的栅格和容器
		SContainerForm col = new SContainerForm();
		ContainerFormcolData colConfig = ContainerFormcolData.makeDefault();
		col.setHostId(hostId).setSiteId(siteId).setFormId(formId).setBoxId(boxId).setParentId(topBox.getId()).setTypeId(6L).setStatus((short) 0).setName("")
				.setOrderNum(colOrder).setConfig(objectMapper.writeValueAsString(colConfig));
		SContainerForm insertCol = sContainerFormServiceImpl.insert(col);
		if (insertCol == null || insertCol.getId() == null) {
			throw new RuntimeException("写入表单下的 col 数据失败！col: " + col);
		}
		SContainerForm box = new SContainerForm();
		ContainerFormboxData boxConfig = ContainerFormboxData.makeDefault();
		box.setHostId(hostId).setSiteId(siteId).setFormId(formId).setBoxId(boxId).setParentId(insertCol.getId()).setTypeId(7L).setStatus((short) 0).setName("")
				.setOrderNum(1).setConfig(objectMapper.writeValueAsString(boxConfig));
		SContainerForm insertBox = sContainerFormServiceImpl.insert(box);
		if (insertBox == null || insertBox.getId() == null) {
			throw new RuntimeException("写入表单下col 的 box 数据失败！topBox: " + box);
		}

		return insertBox;
	}

	@Override
	public RequestGetFormCompSetup getgetFormCompSetup(SForm sForm) throws IOException {
		long hostId = requestHolder.getHost().getId();
		long siteId = requestHolder.getCurrentSite().getId();
		Long formId = sForm.getId();

		RequestGetFormCompSetup result = new RequestGetFormCompSetup();
		result.setFormId(formId);

		FormContSetup formContSetup = new FormContSetup();
		// 获取表单容器的顶级容器
		SContainerForm containerFormmainbox = sContainerFormServiceImpl.findContainerFormmainbox(hostId, formId);
		formContSetup.setContId(containerFormmainbox.getId());

		// 获取所有跟formId关联的s_system数据。
		List<SSystem> systemList = systemServiceImpl.getInfosByHostSiteFormId(hostId, siteId, formId);
		if (CollUtil.isNotEmpty(systemList)) {
			for (SSystem system : systemList) {
				Long systemTypeId = system.getSystemTypeId();
				if (systemTypeId.longValue() == 3) {
					ProductSysConfig sysConfig = SystemConfigUtil.productSysConfig(system);
					String messageText = sysConfig.getItext().getMessageText();
					formContSetup.setFormName(messageText);
				}
			}
		} else {
			formContSetup.setFormName(sForm.getName());
		}

		String config = containerFormmainbox.getConfig();
		ContainerFormmainboxData containerFormmainboxData = objectMapper.readValue(config, ContainerFormmainboxData.class);
		// 验证码
		formContSetup.setVcodePlaceHolder(containerFormmainboxData.getVcodePlaceHolder());
		// 按钮文本，提交
		formContSetup.setButtomText(containerFormmainboxData.getButtomText());
		// 成功-弹窗标题
		formContSetup.setSuccessTitleText(containerFormmainboxData.getSuccessTitleText());
		// 成功-弹窗按钮
		formContSetup.setSuccessButtonText(containerFormmainboxData.getSuccessButtonText());
		// 失败-弹窗标题
		formContSetup.setErrorTitleText(containerFormmainboxData.getErrorTitleText());
		// 失败-弹窗按钮
		formContSetup.setErrorButtonText(containerFormmainboxData.getErrorButtonText());
		// 提交成功！
		formContSetup.setRequestSuccess(containerFormmainboxData.getRequestSuccess());
		// 请输入4位验证码！
		formContSetup.setCaptchaRuleText(containerFormmainboxData.getCaptchaRuleText());
		// 输入的验证码不匹配
		formContSetup.setCaptchaValid(containerFormmainboxData.getCaptchaValid());

		// 写入返回的结果类中
		result.setContSetup(formContSetup);

		// 表单组件项
		List<SComponentForm> sComponentFormList = sComponentFormServiceImpl.findInfosByHostFormIdStatus(hostId, formId, (short) 0);
		List<FormCompSetup> compListSetup = new ArrayList<>(sComponentFormList.size());
		if (CollUtil.isNotEmpty(sComponentFormList)) {
			for (SComponentForm sComponentForm : sComponentFormList) {
				FormCompSetup formCompSetup = new FormCompSetup();
				formCompSetup.setCompId(sComponentForm.getId());

				config = sComponentForm.getConfig();
				Long typeId = sComponentForm.getTypeId();
				formCompSetup.setCompTypeId(typeId);
				List<ComponentFormRules> rules = null;
				if (typeId != null && typeId.longValue() == 20L) {
					ComponentFormtextData componentFormtextData = objectMapper.readValue(config, ComponentFormtextData.class);
					ComponentFormtextDataText text = componentFormtextData.getText();
					formCompSetup.setLabel(text.getLabel());
					formCompSetup.setSetupLabel(text.getLabel());
					formCompSetup.setSetupPlaceholder(text.getPlaceholder());
					rules = componentFormtextData.getRules();
				} else if (typeId != null && typeId.longValue() == 21L) {
					ComponentFormtextareaData componentFormtextareaData = objectMapper.readValue(config, ComponentFormtextareaData.class);
					ComponentFormtextareaDataText text = componentFormtextareaData.getText();
					formCompSetup.setLabel(text.getLabel());
					formCompSetup.setSetupLabel(text.getLabel());
					formCompSetup.setSetupPlaceholder(text.getPlaceholder());
					rules = componentFormtextareaData.getRules();
				}

				List<FormCompSetupRule> ruleList = new ArrayList<>(rules.size());
				if (CollUtil.isNotEmpty(rules)) {
					for (ComponentFormRules componentFormRules : rules) {
						FormCompSetupRule formCompSetupRule = new FormCompSetupRule();

						String rule = componentFormRules.getRule();
						String value = componentFormRules.getValue();
						String defaultMessage = componentFormRules.getDefaultMessage();
						formCompSetupRule.setRule(rule);
						formCompSetupRule.setValue(value);
						formCompSetupRule.setDefaultMessage(defaultMessage);

						ruleList.add(formCompSetupRule);
					}
				}
				formCompSetup.setRules(ruleList);
				compListSetup.add(formCompSetup);
			}
		}

		result.setCompListSetup(compListSetup);

		return result;
	}

	@Override
	@Transactional
	public JsonResult saveFormCompSetup(RequestGetFormCompSetup getFormCompSetup) throws IOException {
		long hostId = requestHolder.getHost().getId();
		long siteId = requestHolder.getCurrentSite().getId();
		long formId = getFormCompSetup.getFormId();
		SForm sForm = getCurrentInfo(formId);
		if (sForm == null) {
			return JsonResult.illegal();
		}

		FormContSetup contSetup = getFormCompSetup.getContSetup();
		List<FormCompSetup> compListSetup = getFormCompSetup.getCompListSetup();

		long contId = contSetup.getContId();
		SContainerForm containerFormmainbox = sContainerFormServiceImpl.findContainerFormmainbox(contId, hostId, formId);
		if (containerFormmainbox == null) {
			String msg = "通过 contId, hostId, formId 未能获取到 SContainerForm 数据，contId=" + contId + ", hostId=" + hostId + ", formId" + formId;
			log.error(msg);
			return JsonResult.illegal();
		}

		// 修改 formName ，两个地方要修改，一个是表单的名称，另外一个是系统配置中的 messageText 字段
		String formName = contSetup.getFormName();
		sForm.setName(formName);
		sFormFeign.updateById(sForm);
		// 获取所有跟formId关联的s_system数据。
		List<SSystem> systemList = systemServiceImpl.getInfosByHostSiteFormId(hostId, siteId, formId);
		if (CollUtil.isNotEmpty(systemList)) {
			for (SSystem system : systemList) {
				Long systemTypeId = system.getSystemTypeId();
				if (systemTypeId.longValue() == 3) {
					ProductSysConfig sysConfig = SystemConfigUtil.productSysConfig(system);
					sysConfig.getItext().setMessageText(formName);
					system.setConfig(objectMapper.writeValueAsString(sysConfig));
					systemServiceImpl.updateSSystem(system);
				}
			}
		}

		String config = containerFormmainbox.getConfig();
		ContainerFormmainboxData containerFormmainboxData = objectMapper.readValue(config, ContainerFormmainboxData.class);
		// 验证码
		containerFormmainboxData.setVcodePlaceHolder(contSetup.getVcodePlaceHolder());
		// 按钮文本，提交
		containerFormmainboxData.setButtomText(contSetup.getButtomText());
		// 成功-弹窗标题
		containerFormmainboxData.setSuccessTitleText(contSetup.getSuccessTitleText());
		// 成功-弹窗按钮
		containerFormmainboxData.setSuccessButtonText(contSetup.getSuccessButtonText());
		// 失败-弹窗标题
		containerFormmainboxData.setErrorTitleText(contSetup.getErrorTitleText());
		// 失败-弹窗按钮
		containerFormmainboxData.setErrorButtonText(contSetup.getErrorButtonText());
		// 提交成功！
		containerFormmainboxData.setRequestSuccess(contSetup.getRequestSuccess());
		// 请输入4位验证码！
		containerFormmainboxData.setCaptchaRuleText(contSetup.getCaptchaRuleText());
		// 输入的验证码不匹配
		containerFormmainboxData.setCaptchaValid(contSetup.getCaptchaValid());
		// 写入配置
		containerFormmainbox.setConfig(objectMapper.writeValueAsString(containerFormmainboxData));
		sContainerFormServiceImpl.update(containerFormmainbox);

		// 表单项修改
		if (CollUtil.isNotEmpty(compListSetup)) {
			for (FormCompSetup formCompSetup : compListSetup) {
				long compId = formCompSetup.getCompId();
				SComponentForm sComponentForm = sComponentFormServiceImpl.findSComponentForm(compId, hostId, siteId, formId);
				
				config = sComponentForm.getConfig();
				Long typeId = sComponentForm.getTypeId();
				List<ComponentFormRules> componentFormRulesList = new ArrayList<>();
				if (typeId != null && typeId.longValue() == 20L) {
					ComponentFormtextData componentFormtextData = objectMapper.readValue(config, ComponentFormtextData.class);
					ComponentFormtextDataText text = componentFormtextData.getText();
					text.setLabel(formCompSetup.getSetupLabel());
					text.setPlaceholder(formCompSetup.getSetupPlaceholder());
					
					List<FormCompSetupRule> rules = formCompSetup.getRules();
					if(CollUtil.isNotEmpty(rules)) {
						for(FormCompSetupRule formCompSetupRule:rules) {
							ComponentFormRules componentFormRules = new ComponentFormRules();
							componentFormRules.setRule(formCompSetupRule.getRule());
							componentFormRules.setValue(formCompSetupRule.getValue());
							componentFormRules.setDefaultMessage(formCompSetupRule.getDefaultMessage());
							componentFormRulesList.add(componentFormRules);
						}
					}
					
					componentFormtextData.setRules(componentFormRulesList);
					sComponentForm.setConfig(objectMapper.writeValueAsString(componentFormtextData));
				} else if (typeId != null && typeId.longValue() == 21L) {
					ComponentFormtextareaData componentFormtextareaData = objectMapper.readValue(config, ComponentFormtextareaData.class);
					ComponentFormtextareaDataText text = componentFormtextareaData.getText();
					text.setLabel(formCompSetup.getSetupLabel());
					text.setPlaceholder(formCompSetup.getSetupPlaceholder());
					
					List<FormCompSetupRule> rules = formCompSetup.getRules();
					if(CollUtil.isNotEmpty(rules)) {
						for(FormCompSetupRule formCompSetupRule:rules) {
							ComponentFormRules componentFormRules = new ComponentFormRules();
							componentFormRules.setRule(formCompSetupRule.getRule());
							componentFormRules.setValue(formCompSetupRule.getValue());
							componentFormRules.setDefaultMessage(formCompSetupRule.getDefaultMessage());
							componentFormRulesList.add(componentFormRules);
						}
					}
					
					componentFormtextareaData.setRules(componentFormRulesList);
					sComponentForm.setConfig(objectMapper.writeValueAsString(componentFormtextareaData));
				}
				
				sComponentFormServiceImpl.update(sComponentForm);
				
			}
		}

		return JsonResult.messageSuccess(getgetFormCompSetup(sForm));
	}

}
